package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class NewInterceptor implements HandlerInterceptor {
    private StringRedisTemplate stringRedisTemplate;

    public NewInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头获取token
        String token = request.getHeader("authorization");
        //判断是否为空
        if (StrUtil.isBlank(token)) {
            return true;
        }
        //从redis获取用户
        Map<Object, Object> user = stringRedisTemplate.opsForHash().entries("login:user:" + token);
        //判断
        if (user.isEmpty()) {
            return true;
        }
        //保存用户到Threadlocal
        //将map集合转为dto false有异常抛出
        UserDTO userDTO = BeanUtil.fillBeanWithMap(user, new UserDTO(), false);
        UserHolder.saveUser(userDTO);
        //设置刷新时间
        stringRedisTemplate.expire("login:user:" + token,30, TimeUnit.MINUTES);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除用户
        UserHolder.removeUser();
    }
}
